﻿(function () {
    "use strict";

    angular
        .module("codeVerificationSystem")
        .controller("RegistrationCtrl",
        ["userAccount",
            "currentUser",
            "$uibModalInstance",
            RegistrationCtrl]);


    function RegistrationCtrl(userAccount, currentUser, $uibModalInstance) {
        var vm = this;

        vm.registerUser = function () {
            userAccount.registration.registerUser(vm.userData,
                function (data) {
                    alert("Успешна регистрация!");
                    vm.confirmPassword = "";
                    vm.message = "... Registration successful";
                    vm.login();
                    vm.cancel();
                },
                function (response) {
                    vm.isLoggedIn = false;
                    vm.message = response.statusText + "\r\n";
                    if (response.data.exceptionMessage)
                        vm.message += response.data.exceptionMessage;

                    // Validation errors
                    if (response.data.modelState) {
                        for (var key in response.data.modelState) {
                            vm.message += response.data.modelState[key] + "\r\n";
                        }
                    }

                    alert(vm.message);
                });
        };
        vm.cancel = function () {
            $uibModalInstance.dismiss();
        };

        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;

            userAccount.login.loginUser(vm.userData,
                function (data) {
                    currentUser.setProfile(vm.userData.userName, JSON.parse(data.roles), data.access_token);
                },
                function (response) {

                });
        };
    }
}());
